import React, { forwardRef, useEffect, useRef, useState, useImperativeHandle } from 'react';
import center from '@turf/center';
import { addLineLayer } from 'src/utils/mapFactory';
import classNames from 'classnames/bind';
import setting from './setting';
import DoubleInput from '../DoubleInput';
import styled from './index.less';
import DrawUtil from '../drawUtil';
import CarList from '../CarList';

const classes = classNames.bind(styled);

const AnalyzeTools = forwardRef(({ justMap, config, editable, bigScreen, events, settingData, data }, ref) => {
  const [utilPreview, setUtilsPreview] = useState(false);
  const [resultPreview, setResultPreview] = useState(false);
  const [dataInfo, setDataInfo] = useState([]);
  const [selectedId, setSelectedId] = useState('');
  const drawUtilRef = useRef();
  const geom = useRef();
  const {
    analyBoxConfig: { analyBoxPriview },
    resultConfig: { resultPriview, resultDisplay },
  } = config;

  // 分析按钮样式
  const analyzeButStyle = () => {
    const {
      butConfig: { butBgColor, butBorderSize, butBorderColor, butFontCode, butSize, butPosition, bgBlur },
    } = config;

    const [w, h] = butSize.split(',');
    const [x, y] = butPosition.split(',');

    return {
      backdropFilter: `blur(${bgBlur}px)`,
      border: `${butBorderSize}px ${butBorderColor} solid`,
      backgroundColor: butBgColor,
      ...butFontCode,
      width: `${w}px`,
      height: `${h}px`,
      left: `${x}px`,
      top: `${y}px`,
      display: 'flex',
    };
  };

  // 分析框样式
  const analyzeBoxStyle = (inside) => {
    const {
      analyBoxConfig: { analyPosition, analySize, analyBgColor, bgBlur, ...insideStyle },
    } = config;
    const [w, h] = analySize.split(',');
    const [x, y] = analyPosition.split(',');
    if (inside) {
      return {
        ...insideStyle,
        butSize: Math.round(h / 1.5),
      };
    }
    return {
      backdropFilter: `blur(${bgBlur}px)`,
      backgroundColor: analyBgColor,
      width: `${w}px`,
      height: `${h}px`,
      left: `${x}px`,
      top: `${y}px`,
    };
  };

  // 分析结果列表样式
  const resultBoxStyle = (type) => {
    const {
      resultConfig: { defaultConfig, activeConfig },
    } = config;
    const { resultPosition, resultSize, resultBg, bgBlur, bgImg } = defaultConfig;
    if (type === 'default') {
      return defaultConfig;
    }
    if (type === 'active') {
      return activeConfig;
    }
    const [w, h] = resultSize.split(',');
    const [x, y] = resultPosition.split(',');
    const result = {
      backdropFilter: `blur(${bgBlur}px)`,
      backgroundColor: resultBg,
      width: `${w}px`,
      height: `${h}px`,
      left: `${x}px`,
      top: `${y}px`,
    };
    if (bgImg) {
      result.backgroundImage = `url(${bgImg})`;
      result.backgroundSize = `${w - 2}px ${h - 2}px`;
      result.backgroundPosition = 'center';
    }
    return result;
  };

  // 更新store中的dataPoll
  const comSetDataPool = (dataPoll) => {
    const { setDataPool } = bigScreen;
    const { click } = events;
    setDataPool(click, dataPoll);
  };

  // 处理圈选事件
  const handleDrawEvent = ({ features, remove }) => {
    const { map } = justMap;
    const { drawConfig } = config;
    const centerFeature = center(features);
    if (centerFeature.geometry.coordinates.length !== 0) {
      // 删除上次圈选内容
      remove();
      // 将圈选数据赋值到变量
      geom.current = `Polygon((${features.features[0].geometry.coordinates.map((item) => item.join(':').replaceAll(',', ' ').replaceAll(':', ','))}))`;
      comSetDataPool({ polygon: geom.current, id: '' });
      // 增加圈选范围图层
      features && addLineLayer(map).create(features, drawConfig);
      // 重置分析工具按钮状态
      drawUtilRef.current.resetButStatus();
    }
  };

  // 处理关闭
  const handleClose = () => {
    // 清空范围缓存数据
    geom.current = '';
    // 清空变量
    comSetDataPool({ polygon: '', id: '' });
    if (justMap) {
      // 删除边界
      addLineLayer(justMap.map).remove();
      // 重置分析工具按钮状态
      drawUtilRef.current && drawUtilRef.current.resetButStatus();
      // 清空选择ID
      setSelectedId('');
      // 隐藏圈选工具
      setUtilsPreview(false);
      // 隐藏圈选结果框
      setResultPreview(false);
    }
  };

  // 处理单击
  const handleButClick = () => {
    const newStatus = !utilPreview;
    if (newStatus === false) {
      handleClose();
    }
    setUtilsPreview(newStatus);
  };

  // 处理查询结果选择的ID
  const handleSelectedClick = (id) => {
    setSelectedId(id);
    comSetDataPool({ polygon: geom.current, id });
  };

  // 卸载组件清空状态
  useEffect(
    () => () => {
      handleClose();
    },
    [justMap]
  );

  // 初始化变量
  useEffect(() => {
    handleClose();
  }, []);

  // 填写变量名名时，初始化变量
  useEffect(() => {
    comSetDataPool({ polygon: '', id: '' });
  }, [JSON.stringify(events)]);

  // 分析工具按钮预览设置
  useEffect(() => {
    if (editable && justMap) {
      setUtilsPreview(analyBoxPriview);
    } else {
      setUtilsPreview(false);
    }
  }, [analyBoxPriview, justMap]);

  // 编辑态预览分析结果
  useEffect(() => {
    if (editable && justMap) {
      setResultPreview(resultPriview);
    } else {
      setResultPreview(false);
    }
  }, [resultPriview, justMap]);

  // 交互引擎控制显隐
  useEffect(() => {
    if (geom.current) {
      setResultPreview(resultDisplay);
    }
  }, [resultDisplay]);

  // 分析结果预览设置
  useEffect(() => {
    if (data) {
      setDataInfo(data);
      geom.current && setResultPreview(true);
    }
  }, [JSON.stringify(data)]);

  useImperativeHandle(ref, () => ({
    useWatchDataPool: (key, datapool) => {
      if (settingData.type === 1) {
        // 如果是静态数据，根据圈选变量值设置结果列表
        // 此逻辑主要是静态数据展示圈选结果使用
        const myKey = events.click.fields.polygon.mapper;

        if (myKey === key) {
          const value = datapool[key];
          if (value !== '') {
            setResultPreview(true);
          } else {
            setResultPreview(false);
          }
        }
      }
    },
  }));

  if (!justMap) return null;

  const dStyle = resultBoxStyle('default');
  const aStyle = resultBoxStyle('active');
  return (
    <div className={styled['analyze-box']}>
      <div className={styled['analyze-but']} style={analyzeButStyle()} onClick={handleButClick}>
        <div>时空分析</div>
      </div>
      <div className={classes('analyze-content', utilPreview ? 'analyze-content-show' : '')} style={analyzeBoxStyle()}>
        <DrawUtil ref={drawUtilRef} justMap={justMap} insideStyle={analyzeBoxStyle(true)} handleDrawEvent={handleDrawEvent}></DrawUtil>
      </div>
      <div className={classes('analyze-content', resultPreview ? 'analyze-content-show' : '')} style={resultBoxStyle()}>
        <div className={styled['result-content']}>
          <div
            className={styled['result-title']}
            style={{
              ...dStyle.titleFontCode,
              borderBottom: dStyle.bgImg ? '0px' : ' 1px solid',
              borderColor: dStyle.titleFontCode.color,
            }}
          >
            <div>搜索结果</div>
            <div style={{ cursor: 'pointer' }} onClick={handleClose}>
              X
            </div>
          </div>
          <div className={styled['result-body']}>
            {dataInfo.map((m) => (
              <CarList
                aStyle={aStyle}
                dStyle={dStyle}
                isSelected={selectedId === m.id}
                className={styled['car-list']}
                onClick={() => {
                  handleSelectedClick(m.id);
                }}
              >
                <div className={styled.text} title={m.text}>
                  {m.text}
                </div>
                <div className={styled.body} title={m.desc}>
                  {m.desc}
                </div>
              </CarList>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
});

AnalyzeTools.setting = setting;
AnalyzeTools.styleConfig = {
  doubleInput: (props) => <DoubleInput {...props} />,
};
export default AnalyzeTools;
